package com.ldc.security.filter;

import com.ldc.common.constants.ConstantsParams;
import com.ldc.common.utils.JwtTokenUtils;
import com.ldc.security.utils.SecurityHttpUtils;
import com.ldc.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检车JWT token 信息
 * 每个请求必须带有token
 *
 * @auther liudc
 * @since 2022/11/13
 */
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    private final Logger logger = LoggerFactory.getLogger(JwtAuthorizationFilter.class);

    @Autowired
    private SecurityUtils securityUtils;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        final String token = SecurityHttpUtils.getToken(request);
        if (StringUtils.isNotEmpty(token) && JwtTokenUtils.checkToken(token)) {
            logger.info("token = {}", token);
            final String userName = (String) JwtTokenUtils.getMapperValue(token, ConstantsParams.USER_NAME);
            logger.info("username ={}", userName);
            if (null == securityUtils) {
                logger.info("{}", "userDetailsService 未被初始化~~");
                throw new ServletException("userDetailsService 未被初始化~~");
            }
            UserDetails userBean = securityUtils.loadUserByUsername(userName);
            if (null == userBean) {
                logger.info("{}", "获取凭证失败~");
                throw new ServletException("获取凭证失败~");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, userBean, userBean.getAuthorities());
            // 更新验证信息
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
